<template>
  <div ref="TablesBox">
    <a-form-model style="padding-top: 10px; height: 100px;" layout="inline" :model="conditions"
                  class="demo-form-inline">
      <a-form-model-item style="margin-left: 10px;" v-for="(c, index) in conditionList"
                         v-bind:key="index" :label="c.label">
        <a-input clearable
                 style="width: 200px;"
                 v-if="c.type === 'input'"
                 :placeholder="c.desc"
                 v-model="conditions[c.modelName]"
        />
        <a-select
            clearable
            @change="changeMoreSelect"
            @deselect="outSelect(conditions[c.modelName])"
            style="width: 200px;"
            mode="multiple"
            v-if="c.type === 'moreSelect'"
            readonly
            :maxTagCount="1"
            :placeholder="c.desc"
            v-model="conditions[c.modelName]"
        >
          <a-select-option
              v-for="item in c.init"
              :value="item.itemCode"
              v-bind:key="item.itemCode"
          >{{ item.itemName }}
          </a-select-option>
        </a-select>
        <a-select
            clearable
            style="width: 200px;"
            show-search
            v-if="c.type === 'select'"
            :placeholder="c.desc"
            v-model="conditions[c.modelName]"
            :filter-option="filterOption"
        >
          <!--          <a-select-option value="">-->
          <!--            全部-->
          <!--          </a-select-option>-->
          <a-select-option
              v-for="item in c.init"
              :value="item.itemCode"
              v-bind:key="item.itemCode"
          >{{ item.itemName }}
          </a-select-option>
        </a-select>
        <a-date-picker clearable
                       style="width: 200px;"
                       v-if="c.type === 'date'"
                       :placeholder="c.desc"
                       v-model="conditions[c.modelName]"
                       value-format="YYYY-MM-DD"
        />
        <a-date-picker show-time
                       clearable
                       style="width: 200px;"
                       v-if="c.type === 'datetime'"
                       :placeholder="c.desc"
                       v-model="conditions[c.modelName]"
                       value-format="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-model-item>
      <a-form-model-item style="margin-left: 10px;">
        <a-button type="primary" v-if="searchBtn" icon="search" @click="dataQuery" :loading="loading">查询</a-button>
        <a-dropdown>
          <a-menu slot="overlay" @click="dataExport">
            <a-menu-item :key="1">默认</a-menu-item>
            <a-menu-item :key="2">格式</a-menu-item>
          </a-menu>
          <a-button type="primary" :loading="exportLoading" style="margin-left: 10px;" icon="download">
            导出
            <a-icon type="down"/>
          </a-button>
        </a-dropdown>
        <a-button type="primary" style="margin-left: 10px;" icon="edit" @click="printContext">打印</a-button>
      </a-form-model-item>
    </a-form-model>
    <div>
      <Table ref="Tables" id="print"
             v-bind:projectId="projectId"
             v-bind:queryId="queryId"
             v-bind:fillName="fillName"
             v-bind:conditions="conditions"
             v-bind:tableHeight="tableHeight"
      ></Table>
      <TableMore v-if="projectId_2" ref="TableMore" style="padding-top: 10px;"
                 v-bind:projectId="projectId_2"
                 v-bind:queryId="queryId_2"
                 v-bind:conditions="conditions"
      ></TableMore>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import BasePanel from "./BasePanel";

import Table from "./Table";
import TableMore from "./TableMore";

export default {
  name: "QueryLayout",
  extends: BasePanel,
  components: {
    Table,
    TableMore
  },
  data() {
    return {
      searchBtn: true, // 查询按钮
      // 分页
      pageNumber: 1,
      tableHeight: window.innerHeight - 150,
      totals: 100,
      projectId: "",
      queryId: "",
      fillName: "",
      projectId_2: "",
      queryId_2: "",
      conditionList: {
        type: Array,
        default: () => []
      },
      conditions: {
        // pageNumber: 0,
        // pageSize: 10
      },
      loading: false,
      exportLoading: false,
      userId: ''
    };
  },
  methods: {
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    // 分页设置
    pageChange(current) {
      this.pageNumber = current;
      this.conditions.pageNumber = current - 1;
      this.dataQuery();
    },
    // 时间戳转换字符串
    formatDate(value, type) {
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      if (type === 'yymmdd') {
        return y + "-" + MM + "-" + d;
      } else {
        return y + "-" + MM + "-" + d + " " + h + "：" + m + "：" + s;
      }
    },
    // 查询表格
    dataQuery() {
      this.loading = true;
      for (let i = 0; i < this.conditionList.length; i++) {
        if (this.conditionList[i].type === 'select') {
          for (let j = 0; j < this.conditionList[i].init.length; j++) {
            if (this.conditionList[i].init[j].itemCode === this.conditions[this.conditionList[i].modelName]) {
              this.$set(this.conditions, this.conditionList[i].modelName + 'Name', this.conditionList[i].init[j].itemName);
            }
          }
        }
      }
      this.$refs.Tables.loadData(() => {
        this.loading = false;
      });
      if (this.queryId_2) {
        this.$refs.TableMore.loadData(() => {
          this.loading = false;
        });
      }
    },
    // 导出
    dataExport(e) {
      const conditionsBox = JSON.parse(JSON.stringify(this.conditions));
      this.exportLoading = true;
      this.$set(conditionsBox, 'pagenumber', 1);
      this.$set(conditionsBox, 'pagesize', 99999);
      // 如果为二次表格则转换时间戳格式
      axios
          .post("/api/" +
              this.projectId + "/" + this.queryId + "/" + this.fillName + "/execute",
              conditionsBox
          )
          .then(resp => {
            if (resp.data.code == "500") {
              console.log('错误', resp.data.data);
            } else {
              this.$refs.Tables.dataExcel = resp.data.data;
              // 各表格添加最后一行合计导出
              if (this.projectId === 'gasStation01') {
                // 加油站交易明细
                let SL = 0;
                let V20 = 0;
                for (let i = 0; i < this.$refs.Tables.dataExcel.length; i++) {
                  SL += Number(this.$refs.Tables.dataExcel[i].SL)
                  V20 += Number(this.$refs.Tables.dataExcel[i].V20)
                }
                this.$refs.Tables.dataExcel.push({
                  SJ: '合计',
                  SL: SL.toFixed(2)
                });
              }
              if (e.key === 1) {
                let searchBox = {};
                for (let j = 0; j < this.conditionList.length; j++) {
                  if (this.conditions[this.conditionList[j].modelName]) {
                    if (this.conditionList[j].type === 'select') {
                      this.$set(searchBox, [this.conditionList[j].label], this.conditions[this.conditionList[j].modelName + 'Name']);
                    } else {
                      this.$set(searchBox, [this.conditionList[j].label], this.conditions[this.conditionList[j].modelName]);
                    }
                  }
                }
                const query = Object.keys(searchBox).map(key => `${decodeURI(encodeURIComponent(key))}：${decodeURI(encodeURIComponent(searchBox[key]))}`).join('，');
                let fileName = this.formatDate(new Date()) + "，" + query + '，' + this.$route.query.routerName;
                this.$refs.Tables.dataToExcel(fileName);
              }
              if (e.key === 2) {
                let searchBox = {};
                for (let j = 0; j < this.conditionList.length; j++) {
                  if (this.conditions[this.conditionList[j].modelName]) {
                    if (this.conditionList[j].type === 'select') {
                      this.$set(searchBox, [this.conditionList[j].label], this.conditions[this.conditionList[j].modelName + 'Name']);
                    } else {
                      this.$set(searchBox, [this.conditionList[j].label], this.conditions[this.conditionList[j].modelName]);
                    }
                  }
                }
                const query = Object.keys(searchBox).map(key => `${decodeURI(encodeURIComponent(key))}：${decodeURI(encodeURIComponent(searchBox[key]))}`).join('，');
                let fileName = this.formatDate(new Date()) + "，" + query + '，' + this.$route.query.routerName;
                this.$refs.Tables.dataToExcelFormat(fileName);
              }
              this.exportLoading = false;
            }
          });
    },
    // 打印
    printContext() {
      // this.$refs.Tables.printer();
      // 发送消息
      let msg = {
        command: 'print',
        fileName: this.queryId + '.fr3',
        overRide: 0,
        directPrint: 0,
        sid: this.queryId,
        url: 'http://192.168.22.12:8080/' + this.queryId + '.fr3',
        body: Object.assign(JSON.parse(JSON.stringify(this.conditions)), {
          tableData: this.$refs.Tables.tableData,
        })
      };
      console.log(msg);
      this.$sendMessage(JSON.stringify(msg));
    },
    loadConditions(callback) {
      this.getQueryVariable();
      const conditionsBox = JSON.parse(JSON.stringify(this.conditions));
      axios
          .post("/api/" +
              this.projectId +
              "/" +
              this.queryId +
              "/" +
              this.fillName +
              "/getConditions", conditionsBox
          )
          .then(resp => {
            if (resp.data.code === "500") {
              alert(resp.data.data);
            } else {
              if (resp.data.data) {
                this.searchBtn = true;
                this.conditionList = resp.data.data;
              } else {
                // 如果没有查询条件，则页面跳转时执行
                this.$nextTick(() => {
                  this.conditionList = [];
                  this.searchBtn = false;
                  this.dataQuery();
                });
              }
            }
            callback();
          });
    },
    // 设置url参数到查询条件
    getQueryVariable() {
      let queryHref = window.location.href;
      if (queryHref.indexOf("?") !== -1) {
        let query = queryHref.split("?")[1];
        let vars = query.split("&");
        for (let i = 0; i < vars.length; i++) {
          let pair = vars[i].split("=");
          this.$set(
              this.conditions,
              pair[0],
              decodeURI(pair[1])
          );
        }
      }
      this.userId = this.$route.query.userId;
    },
    setConditionDefaultValue() {
      for (let i = 0; i < this.conditionList.length; i++) {
        let defaultValue = this.conditionList[i].defaultValue;
        if (defaultValue === null) {
          defaultValue = "";
        }
        if (this.conditionList[i].type === "date") {
          if (this.conditionList[i].defaultValue) {
            // 如果是日期控件
            defaultValue = new Date(
                new Date().getTime() +
                Number(defaultValue || "0") * 24 * 3600 * 1000
            ).format("yyyy-MM-dd");
          } else {
            defaultValue = this.formatDate(Number(this.conditionList[i].initDate[0].date), 'yymmdd')
          }
        } else if (this.conditionList[i].type === "datetime") {
          // 如果是时间控件
          defaultValue = new Date(
              new Date().getTime() +
              Number(defaultValue || "0") * 24 * 3600 * 1000
          ).format("yyyy-MM-dd 00:00:00");
        } else if (this.conditionList[i].type === "moreSelect") {
          // 如果是多选框
          defaultValue = [];
        }
        this.$set(this.conditions, this.conditionList[i].modelName, defaultValue);
      }
    },
    // 取消选中
    outSelect(e) {
    },
    // 多选框选中option事件
    changeMoreSelect(e) {
    }
  },
  created() {
    // 动态切换标签页标题
    document.title = this.$route.query.routerName;
    this.projectId = this.$route.params.projectId;
    this.queryId = this.$route.params.queryId;
    this.fillName = this.$route.params.fillName;
  },
  mounted() {
    this.loadConditions(() => {
      this.setConditionDefaultValue();
      this.getQueryVariable();
      this.dataQuery();
    });
  },
  // 监听路由发生变化时刷新信息
  watch: {
    $route(to, from) {
      this.conditions = {};
      this.projectId = this.$route.params.projectId;
      this.queryId = this.$route.params.queryId;
      this.fillName = this.$route.params.fillName;
      // this.$refs.Tables.projectId = this.$route.params.projectId;
      // this.$refs.Tables.queryId = this.$route.params.queryId;
      this.loadConditions(() => {
        this.setConditionDefaultValue();
        this.getQueryVariable();
        this.dataQuery();
      });
    }
  }
};
</script>

<style scoped>
.tableTitle {
  font-size: 20px;
  font-weight: bold;
  padding: 20px 0px 10px 10px;
  text-align: center;
}

.tableSearch {
  padding: 0px 0px 10px 0px;
  font-size: 16px;
}

.tableSpan:first-child {
  margin-left: 10px;
}

.tableSpan {
  margin-right: 20px;
}

/deep/ .ant-select-selection__choice__remove {
  display: none !important;
}

/deep/ .ant-form-item-label {
  width: 70px !important;
}

.c-button {
  color: #fff;
  background-color: #b3232d;
  border-color: #b3232d;
}

.c-button:hover {
  color: #fff;
  background-color: #b3232d;
  border-color: #b3232d;
}

.c-button[disabled], .c-button[disabled]:hover, .c-button[disabled]:focus, .c-button[disabled]:active {
  color: rgba(0, 0, 0, 0.25);
  background: #b3232d;
  border-color: #b3232d;
  text-shadow: none;
  box-shadow: none;
}

.c-button {
  color: #fff;
  background-color: #b3232d;
  border-color: #b3232d;
}

.c-button:hover {
  color: #fff;
  background-color: #b3232d;
  border-color: #b3232d;
}

.c-button[disabled], .c-button[disabled]:hover, .c-button[disabled]:focus, .c-button[disabled]:active {
  color: #FFFFFF;
  background: #b3232d;
  border-color: #b3232d;
  text-shadow: none;
  box-shadow: none;
}

.c-button, .c-button:hover, .c-button:focus, .c-button:active {
  color: #FFFFFF;
  background: #b3232d;
  border-color: #b3232d;
  text-shadow: none;
  box-shadow: none;
}
</style>
